//
//  L_footPlaytabBar.m
//  音悦咖
//
//  Created by dllo on 15/7/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "L_footPlaytabBar.h"
#import "D_DataBase.h"
#import "D_FootCollectionViewCell.h"
#import "STKAudioPlayer.h"
#import "L_RecommendPlayModel.h"
#import "L_PlayListView.h"
@interface L_footPlaytabBar ()

@property (nonatomic, assign) BOOL isCircle;
@property (nonatomic, retain) NSMutableArray *arr1;
@property (nonatomic,retain)  UICollectionView *collecion;
@property (nonatomic,retain) UIView *footView;
@property (nonatomic, retain) L_PlayListView *playlist;


@end

@implementation L_footPlaytabBar


+ (L_footPlaytabBar *)shareTabBar
{
    static L_footPlaytabBar *footPlayTabBarView;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!footPlayTabBarView) {
            footPlayTabBarView = [[L_footPlaytabBar alloc] init];
        }
    });
    return footPlayTabBarView;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.tabBar removeFromSuperview];
//    [self createPlayListViews];
    
//     设置定时器
    self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
    // 定时器暂停
    [self.time setFireDate:[NSDate distantFuture]];
    
    // 单例初始化
    self.single = [L_Singleton shareManager];
    
    // 临时列表数组初始化
    self.single.array = [NSMutableArray array];
    self.single.modelNum = 0;
    
    
    // 创建底部播放视图
    self.footPlayView = [[L_FootPlayVIew alloc] initWithFrame:self.tabBar.frame];
    _footPlayView.backgroundColor = [UIColor greenColor];
    [_footPlayView.playOrPause addTarget:self action:@selector(playOrPauseAction) forControlEvents:UIControlEventTouchUpInside];
    [_footPlayView.nextSong addTarget:self action:@selector(nextSongAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_footPlayView.playList addTarget:self action:@selector(footPlayTapAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_footPlayView.nextSong setImage:[UIImage imageNamed:@"nextSong.png"] forState:UIControlStateNormal];
    [_footPlayView.playOrPause setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    [_footPlayView.playList setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    
    if (self.single.array.count == 0) {
         _footPlayView.mainImage.image = [UIImage imageWithContentsOfFile:GETBUNDLE_PATH(@"lloo", @"png")];
    }
    
    
    [self.view addSubview:_footPlayView];
    [_footPlayView release];
    
    // 底部播放视图添加tap手势
    UITapGestureRecognizer *footPlayTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(footPlayTapAction)];
    [_footPlayView.mainImage addGestureRecognizer:footPlayTap];
    [footPlayTap release];
    

}

#pragma mark - slider事件
- (void)progressAction
{
    
    CGFloat duration = 0;
    
    NSString *songDuration = [[[[self.single.array[self.single.index] url_list] firstObject] objectForKey:@"duration"] description];

    if ([songDuration rangeOfString:@":"].location != NSNotFound) {
    
    NSInteger songTimeMin = [[[[[self.single.array[self.single.index] url_list] firstObject] objectForKey:@"duration"] substringWithRange:NSMakeRange(0, 2)] integerValue];
    NSInteger songTimeSec = [[[[[self.single.array[self.single.index] url_list] firstObject] objectForKey:@"duration"] substringWithRange:NSMakeRange(2, 2)] integerValue];
    
    duration = songTimeMin * 60 + songTimeSec;
    
    } else {
        
        duration = [songDuration floatValue];
        
    }

    //如果播放完，判断播放模式进行播放
    if (self.single.streamer.progress > 0) {

        if (self.single.streamer.progress > duration - 1) {
      
            [self.time invalidate];
            
            self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
            [self playModel:self.single.modelNum];
        }
    }
    
   
}



#pragma mark - 播放模式
- (void)playModel:(NSInteger)model
{
    
    switch (model) {
        case 0:
        {
            // 循环播放
            _isCircle = YES;
            if (_isCircle == YES) {
                self.single.index += 1;
                if (self.single.index == self.single.array.count) {
                    self.single.index = 0;
                }
                
                [self updatePlayerSetting];
                
            }
        }
            break;
            
        case 1:
            {
                
                // 列表播放
                _isCircle = NO;
                self.single.index += 1;
                if (self.single.index >= [self.single.array count]) {
                    [self.single.streamer stop];
                }
                
                [self updatePlayerSetting];
                
            }
            break;
            
        case 2:
            {
                // 随机播放
                _isCircle = NO;
                NSInteger number = [self.single.array count];
                self.single.index =  arc4random() % number;
                [self updatePlayerSetting];
                
            }
            break;
            
        case 3:
            {
                // 单曲循环
                _isCircle = NO;
                [self updatePlayerSetting];
                
            }
            break;
            
        default:
            break;
        }
    
}

#pragma mark - 更新播放器设置
- (void)updatePlayerSetting
{
    // 更新播放按钮状态
    [self.footPlayView.playOrPause setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    self.single.state = nil;
    
    self.single.playUrl = [[[self.single.array[self.single.index] url_list] lastObject] objectForKey:@"url"];
    
//    for (L_RecommendPlayModel *m in self.single.array) {
//        NSLog(@"_+_+_+_+_+_+_+_+%@", m.url_list);
//    }
    
    self.footPlayView.songName.text = [self.single.array[self.single.index] song_name];
    self.footPlayView.songerName.text = [self.single.array[self.single.index] singer_name];
    [self.footPlayView.mainImage setImageWithURL:[NSURL URLWithString:[[[self.single.array[self.single.index] mv_list] firstObject] objectForKey:@"pic_url"]] placeholderImage:[UIImage imageNamed:@"musicbg.jpg"]];
    
    //播放
    [self.single playWithUrl:self.single.playUrl];
    self.single.state = @"playing";
    
    
    
}




#pragma mark - 根部播放(暂停)按钮点击方法
- (void)playOrPauseAction
{
    
    if (self.single.array.count == 0) {
        return;
    } else {
        
        if ([self.single.state isEqualToString:@"playing"]) {
            // 定时器暂停
            [self.time setFireDate:[NSDate distantFuture]];
            [self.single.streamer pause];
            self.single.state = nil;
            [self.footPlayView.playOrPause setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        } else {
            // 定时器开启
            [self.time setFireDate:[NSDate distantPast]];
            [self.single.streamer resume];
            self.single.state = @"playing";
            [self.footPlayView.playOrPause setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
            
        }

        self.footPlayView.songName.text = [self.single.array[self.single.index] song_name];
        self.footPlayView.songerName.text = [self.single.array[self.single.index] singer_name];
        [self.footPlayView.mainImage setImageWithURL:[NSURL URLWithString:[[[self.single.array[self.single.index] mv_list] firstObject] objectForKey:@"pic_url"]] placeholderImage:[UIImage imageNamed:@"musicbg.jpg"]];
    }
    
    
}

#pragma mark - 根部下一首按钮点击方法
- (void)nextSongAction
{
    // 判断是否为空
    if ([self.single.array count] == 0) {
        
    } else {
        // 进行模式进行选择
        [self playModel:self.single.modelNum];
        
    }


}

#pragma mark - 根部播放列表点击方法
- (void)playListAction:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected) {
        [UIView transitionWithView:self.playlist duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            
            self.playlist.frame = CGRectMake(SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3, SCREEN_WIDTH / 4 * 3, SCREEN_HEIGHT / 3 * 2 - 49);
            
        } completion:^(BOOL finished) {
            
            
        }];

    }else{
        
        [UIView transitionWithView:self.footView duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            
            self.playlist.frame = CGRectMake(SCREEN_WIDTH, SCREEN_HEIGHT - 49, 0, 0);
            
        } completion:^(BOOL finished) {
            
        }];
    }
 
}





#pragma mark - 底部播放视图tap手势方法
- (void)footPlayTapAction
{
    PlayViewController *play = [[[PlayViewController alloc] init] autorelease];
    
    play.playView.title.text = self.footPlayView.songName.text;
    play.playView.songerName.text = self.footPlayView.songerName.text;
    play.playView.showImage.image = self.footPlayView.mainImage.image;
    
    // 定时器暂停
    [self.time setFireDate:[NSDate distantFuture]];
    [self presentViewController:play animated:YES completion:^{
        // 模态到音乐播放页面
    }];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
